package com.kevecho.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.io.IOException;
import java.util.Scanner;

/**
 * Hello world!
 *
 */
public class AppPublisher
{
    private MqttClient client;
    private MqttTopic topic;
    private String myTopic = "topic/machine";

    public static void main( String[] args ) throws MqttException {
        Scanner input = new Scanner(System.in);
        AppPublisher publisher = new AppPublisher();
        String val = null;       // 记录输入的字符串
        do{
            System.out.print("请输入：");
            val = input.next();       // 等待输入值
            System.out.println("您输入的是："+val);
            publisher.publish(val);
        }while(!val.equals("#"));   // 如果输入的值不是#就继续输入
        System.out.println("你输入了\"#\"，程序已经退出！");
        input.close(); // 关闭资源
    }

    public AppPublisher() throws MqttException {
        connect();
    }

    public void publish(String input) throws MqttException {
        topic = client.getTopic(myTopic + "/282738");

        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setRetained(true);
        message.setPayload(input.getBytes());

        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
    }

    private void connect() throws MqttException {
        client = new MqttClient("tcp://192.168.242.135:1883", "Server", new MemoryPersistence());

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName("demo");
        options.setPassword("demo".toCharArray());

        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);

        client.setCallback(new MqttCallback() {
            public void connectionLost(Throwable cause) {
                System.out.println("connectionLost-----------");
            }

            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("messageArrived----------" + new String(message.getPayload()));
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("deliveryComplete---------"+token.isComplete());
            }
        });

        client.connect(options);
        client.subscribe(myTopic, 1);
    }
}
